<?php

namespace Admin\Frontend\Controllers;

use Admin\Models\user\XhsysUser;
use Helpers\Tool;
use Helpers\Main;
use Helpers\HttpClient;
use Helpers\Template;
use Helpers\Assets;
use Helpers\User;
use Helpers\XhException;
use Modules\Power;
use Services\App;

class AppgroupController extends ControllerBase
{

    /**
     * @var HttpClient
     */
    private $httpClient;
    private $groupEnum      = [
        'userType'  => [0 => '未知', 1 => '学生', 2 => '教师', 4 => '通用']
    ];
    private $groupTime      = ['createTime', 'updateTime'];
    private $groupAppEnum   = [
        'type'      => [0 => '安装/更新', 1 => '卸载'],
        'userType'  => [1 => '学生', 2 => '教师', 3 => '家长', 4 => '通用']
    ];
    private $groupAppTime   = ['updatedAt'];

    public function initialize()
    {
        $config = Main::getConfigByName('jAppServer');
        $this->httpClient = new HttpClient($config['url']);
    }

    /**
     * 应用组列表
     *
     * create by ck 20170701
     * modify by ck 20170918    支持获取单人所在应用组
     */
    public function appGroupAction()
    {
        $this->view->setTemplateBefore('listForm');
        $schoolId = $this->request->getQuery('schoolId', 'int');
        $userId   = $this->request->getQuery('userId', 'int');
        if (!$schoolId && !$userId) {
            return $this->sendViewError('缺少必要参数');
        }
        if (!Power::exist('School_List_Group')) {
            return $this->sendViewError('无应用组权限');
        }
        Assets::easyUI('js/appgroup/appGroup.js');
        if ($userId) {
            Main::showNavPosition('学校列表', ['学校设置', '用户应用组']);
        } else {
            Main::showNavPosition('学校列表', ['学校设置', '应用组'], true);
        }
        $listSearchArr = $listButtonArr = [];
        if ($schoolId) {
            if (Power::exist('School_List_Group_Add')) {
                $listButtonArr[] = ['id'=>'bt_list_add', 'text'=>'增加', 'icon'=>'fa-plus'];
            }
            if (Power::exist('School_List_Group_Edit')) {
                $listButtonArr[] = ['id'=>'bt_list_edit', 'text'=>'修改', 'icon'=>'fa-pencil'];
                $listButtonArr[] = ['id'=>'bt_list_copy', 'text'=>'复制', 'icon'=>'fa-copy'];
            }
            if (Power::exist('School_List_Group_Clean')) {
                $listButtonArr[] = ['id'=>'bt_list_clean', 'text'=>'一键清理', 'icon'=>'fa-refresh'];
            }
            $listSearchArr[] = ['type' => 'text', 'id' => 'list_vague', 'label' => '搜索：'];
            $listSearchArr[] = ['type' => 'button', 'id' => 'bt_list_search', 'text' => '查找', 'icon' => 'fa fa-search'];
        }
        if (Power::exist('School_List_Group_Edit')) {
            $listButtonArr[] = ['id' => 'bt_list_user', 'text' => '关联用户', 'icon' => 'fa-pencil'];
            $listButtonArr[] = ['id' => 'bt_list_app', 'text' => '关联应用', 'icon' => 'fa-pencil'];
        }
        if (Power::exist('School_List_Group_Del')) {
            $listButtonArr[] = ['id' => 'bt_list_del', 'text' => '删除', 'icon' => 'fa-trash'];
        }
        return $this->view->setVars([
            'List'          => Template::createList('list', 'App_Group', [
                'searchToolbar' => Template::createSearchToolBar($listSearchArr, !!$listButtonArr),
                'buttonToolbar' => Template::createButtonToolBar($listButtonArr),
                'tableAttr'     => $userId ? ['pagination' => 'false'] : []
            ])
        ]);
    }

    /**
     * 获取应用组列表
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20170701
     * modify by ck 20170721    时间戳转换BUG修复
     * modify by ck 20170918    支持获取个人所在应用组
     */
    public function getAppGroupAction()
    {
        $schoolId = $this->request->getPost('schoolId', 'int');
        $userId   = $this->request->getPost('userId', 'int');
        $name     = $this->request->getPost('name', 'string');
        if (!$schoolId && !$userId) {
            return $this->sendErrorResponse(400, '缺少必要参数');
        }
        if ($userId) {
            $response = $this->httpClient->get(sprintf('/api/v1/users/%s/assigned/groups', $userId));
            $body = $response->toArray();
            $data = [
                'total' => count($body),
                'rows' => $body
            ];
        } else {
            $data = App::getAppGroups(
                $this->request->getPost('page', 'int', 1),
                $this->request->getPost('rows', 'int'),
                [
                    'schoolId' => $schoolId,
                    'name'     => $name
                ]
            );
//            $response = $this->httpClient->get('/api/v1/groups/search', [
//                'schoolId'  => $schoolId,
//                'page'      => $this->request->getPost('page', 'int', 1),
//                'size'      => $this->request->getPost('rows', 'int')
//            ]);
//            $body = $response->toArray();
//            if(!$body || $body['totalElements'] === null || $body['content'] === null){
//                return $this->sendErrorResponse(500, '无返回数据', $response);
//            }
//            $data = [
//                'total' => $body['totalElements'],
//                'rows'  => $body['content']
//            ];
        }
        Tool::runTimestamp($data['rows'], $this->groupTime);
        Tool::runEnum($data['rows'], $this->groupEnum);
        //处理注册/安装进度
        foreach ($data['rows'] as $index => $row) {
            $data['rows'][$index]['registeredUserNum'] = $row['registeredUserNum'] . '/' . $row['userNum'];
            $data['rows'][$index]['installedUserNum']  = $row['installedUserNum'] . '/' . $row['userNum'];
        }
        return $this->response->setJsonContent($data);
    }

    /**
     * 新增用户组
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20170701
     * modify by ck 20170825    添加类型
     */
    public function createAppGroupAction()
    {
        $schoolId = $this->request->getPost('schoolId', 'int');
        $groupName = $this->request->getPost('groupName', 'string');
        $groupType = $this->request->getPost('groupType', 'int');
        if (!$schoolId || !$groupName || !$groupType) {
            return $this->sendErrorResponse(400, '缺少必要参数！');
        }
        $jsonBody = [
            'schoolId' => $schoolId,
            'groupName' => $groupName,
            'userType' => intval($groupType)
        ];
        $response = $this->httpClient->postJson('/api/v1/groups/', $jsonBody);
        if (!$response->isSuccess()) {
            $body = $response->toObject();
            return $this->sendErrorResponse(500, '创建失败！', $body->msg ?: $response);
        }
        return $this->sendSuccessResponse('创建成功！');
    }

    /**
     * 更新用户组信息
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20171116
     */
    public function modifyAppGroupAction()
    {
        $groupId   = $this->request->getPost('groupId', 'string');
        $groupName = $this->request->getPost('groupName', 'string');
        $groupType = $this->request->getPost('groupType', 'int');
        if (!$groupId || !$groupName || !$groupType) {
            return $this->sendErrorResponse(400, '缺少必要参数！');
        }
        $jsonBody = [
            'groupName' => $groupName,
            'userType' => intval($groupType)
        ];
        $response = $this->httpClient->putJson(sprintf('/api/v1/groups/%s/info', $groupId), $jsonBody);
        if (!$response->isSuccess()) {
            $body = $response->toObject();
            return $this->sendErrorResponse(500, '修改失败', $body->msg ?: $response);
        }
        return $this->sendSuccessResponse('修改成功');
    }

    /**
     * 删除用户组
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20170702
     */
    public function delAppGroupAction()
    {
        $ids = $this->request->getPost('ids', 'string');
        if (!$ids) {
            return $this->sendErrorResponse(400, '组id不能为空！');
        }
        $response = $this->httpClient->delete(sprintf('/api/v1/groups/%s', $ids[0]));
        if (!$response->isSuccess()) {
            $body = $response->toObject();
            return $this->sendErrorResponse(500, '删除失败！', $body->msg ?: $response);
        }
        return $this->sendSuccessResponse('删除成功！');
    }

    /**
     * 复制应用组
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20180420
     */
    public function copyGroupAction()
    {
        $groupId = $this->request->getPost('groupId', 'string');
        if (!$groupId) {
            return $this->sendErrorResponse(400, '缺少组id！');
        }
        $response = $this->httpClient->post(sprintf('/api/v1/groups/%s/copy', $groupId));
        if (!$response->isSuccess()) {
            return $this->sendErrorResponse(500, '复制失败', $response);
        }
        return $this->sendSuccessResponse('复制成功');
    }

    /**
     * 应用组用户页面
     *
     * create by ck 20170702
     * modify by ck 20170705    添加搜索工具条
     */
    public function appGroupUserAction()
    {
        $this->view->pick('appgroup/appGroupUser');
        $groupId = $this->request->getQuery('groupId', 'string');
        $groupId or die(Main::showMessageModal('缺少用户组ID！', true));
        Assets::easyUI('js/appgroup/appGroupUser.js');
        $outListSearchArr = [];
        $outListSearchArr[] = ['type'=>'select', 'id'=>'list_out_history', 'style' => 'width: 60px;', 'data' => [
            0 => '正常',
            1 => '历史']
        ];
        $outListSearchArr[] = ['type' => 'select', 'id' => 'list_out_user_type', 'style' => 'width:60px;', 'data' => [
            '' => '-身份-',
            '1' => '学生',
            '4' => '教师',
        ]];
        $outListSearchArr[] = ['type' => 'select', 'id' => 'list_out_subject', 'style' => 'width:60px;',
            'data' => ['' => '-科目-'] + User::getEnum('iSubject')];
        $outListSearchArr[] = ['type' => 'select', 'id' => 'list_out_item', 'multiple' => 'true',
            'style' => 'width:80px;', 'data' => [
                '' => '-条件-',
                'sAdClsName' => '班级',
                'sUserName' => '姓名',
                'sLogonName' => '登陆名',
            ]];
        $outListSearchArr[] = ['type'=>'text', 'id'=>'list_out_vague'];
        $outListSearchArr[] = ['type'=>'button', 'id'=>'bt_list_out_search', 'text'=>'查找',
            'icon'=>'fa-search', 'style'=>'margin-left:10px'];
        $this->view->setVars([
            'InList'    => Template::createList('list_in', 'App_GroupUser', [
                'title'         => '已关联用户',
                'tableAttr'     => ['pagination' => 'false']
            ]),
            'OutList'   => Template::createList('list_out', 'App_GroupUser', [
                'title'         => '用户列表',
                'searchToolbar' => Template::createSearchToolBar($outListSearchArr)
            ]),
        ]);
    }

    /**
     * 查找用户
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20181110
     * modify by ck 20181112
     */
    public function getUserForAppGroupAction()
    {
        $schoolId = $this->request->getPost('schoolId', 'int');
        $userType = $this->request->getPost('userType', 'int');
        $history = $this->request->getPost('history', 'int', 0);
        $subject = $this->request->getPost('subject', 'int');
        $items = array_filter($this->request->getPost('items', 'string'));
        $vague = $this->request->getPost('vague', 'string');
        if (!$schoolId) {
            return $this->sendErrorResponse(400, '学校id不能为空');
        }
        try {
            $sql = "SELECT u.iUserId,u.sUserName,u.sLogonName,u.iUserType,u.sAdClsName,u.iUserSex,u.bHistory,t.iSubject
              FROM XHSys_User u
              LEFT JOIN XHSys_UserTch t ON u.iUserId = t.iUserId
              WHERE u.bDelete = 0 AND u.bDisable = 0 AND u.bHistory = '{$history}' AND u.iSchoolId = {$schoolId}";
            if ($userType) {
                $sql .= " AND u.iUserType = '{$userType}'";
            }
            if ($subject) {
                $sql .= " AND t.iSubject = '{$subject}'";
            }
            $sql .= Main::runVagueCondition($items ?: ['u.sAdClsName', 'u.sUserName', 'u.sLogonName'], $vague);
            $data = Main::runSqlPage($sql, User::getEnum());
            return $this->sendJsonResponse($data);
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, '系统异常', $e->getMessage());
        }
    }

    /**
     * 获取用户组用户
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20170702
     * modify by ck 20180730
     * modify by ck 20181108
     * modify by ck 20181113
     */
    public function getAppGroupUserAction()
    {
        $groupId = $this->request->getPost('groupId', 'string');
        if (!$groupId) {
            return $this->sendErrorResponse(400, '缺少用户组ID！');
        }
        $userIdArr = App::getAppGroupUser($groupId);
//        $response = $this->httpClient->get(sprintf('/api/v1/groups/%s', $groupId));
//        if(!$response->isSuccess()){
//            $body = $response->toObject();
//            return $this->sendErrorResponse(500, '获取失败！', $body->msg ?: $response);
//        }
//        $body = $response->toArray();
//        $userIdArr = $body['userIdList'] ?: [];
        if (!$userIdArr) {
            return $this->response->setJsonContent(['total' => 0, 'rows' => []]);
        }
        $userIds = implode(',', $userIdArr);
        $sql = "SELECT u.iUserId,u.sUserName,u.sLogonName,u.iUserType,u.sAdClsName,u.iUserSex,u.bHistory,t.iSubject
              FROM XHSys_User u
              LEFT JOIN XHSys_UserTch t ON u.iUserId = t.iUserId
              WHERE u.bDelete = 0 AND u.iUserId IN ({$userIds})";
        $data = Main::runSqlPage($sql, User::getEnum());
//        $parameters = [
//            'columns'    => 'iUserId,sUserName,sLogonName,iUserType,sAdClsName,iUserSex,bHistory',
//            'conditions' => 'bDelete = 0 AND iUserId IN ({idArr:array})',
//            'bind'       => ['idArr' => $userIdArr]
//        ];
//        $data = Main::runModelPage('\\Admin\\Models\\user\\XhsysUser', $parameters, User::getEnum());
        return $this->response->setJsonContent($data);
    }

    /**
     * 更改用户组用户
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20170702
     * modify by ck 20180730
     */
    public function modifyAppGroupUserAction()
    {
        $groupId = $this->request->getPost('groupId', 'string');
        $userIds = $this->request->getPost('userIds', 'int');
        if (!$groupId) {
            return $this->sendErrorResponse(400, '缺少用户组ID！');
        }
        try {
            App::modifyAppGroupUser($groupId, $userIds);
            return $this->sendSuccessResponse('保存成功！');
        } catch (XhException $e) {
            return $this->sendErrorResponse(500, $e->getMessage(), $e->getDescription());
        }
//        $requestUserId = [];
//        foreach($userIds as $userId){
//            $requestUserId[] = ['id' => $userId];
//        }
//        $this->httpClient->setHeader('Content-Type', 'application/json');
//        $response = $this->httpClient->put(sprintf('/api/v1/groups/%s', $groupId), json_encode(['userIdList' => $requestUserId]));
//        if(!$response->isSuccess()){
//            $body = $response->toObject();
//            return $this->sendErrorResponse(500, '保存失败！', $body->msg ?: $response);
//        }
//        return $this->sendSuccessResponse('保存成功！');
    }

    /**
     * 应用组应用展示页面
     *
     * create by ck 20170703
     * modify by ck 20170704    使用不同列表
     */
    public function appGroupAppAction()
    {
        $this->view->pick('appgroup/appGroupApp');
        $groupId = $this->request->getQuery('groupId', 'string');
        if (!$groupId) {
            return $this->sendViewError('缺少用户组id');
        }
        Assets::easyUI('js/appgroup/appGroupApp.js');
        $notListSearchArr = [];
        $notListSearchArr[] = ['type' => 'text', 'id' => 'list_not_vague', 'label' => '搜索：'];
        $notListSearchArr[] = ['type' => 'button', 'id' => 'bt_list_not_search', 'text' => '查找', 'icon' => 'fa-search'];
        return $this->view->setVars([
            'InList'    => Template::createList('InList', 'App_GroupApp', [
                'title'     => '已关联',
                'tableAttr' => ['pagination' => 'false', 'singleSelect' => 'true']
            ]),
            'NotList'   => Template::createList('OutList', 'App_GroupAppOut', [
                'title'         => '选择应用',
                'tableAttr'     => ['singleSelect' => 'false'],
                'searchToolbar' => Template::createSearchToolBar($notListSearchArr)
//                'field'     => ['appId', 'name', 'packageName', 'userType', 'versionCode', 'versionName', 'verCreateTime']
            ]),
        ]);
    }

    /**
     * 获取应用组应用
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20170704
     */
    public function getAppGroupAppAction()
    {
        $groupId = $this->request->getPost('groupId', 'string');
        if(!$groupId){
            return $this->sendErrorResponse(400, '应用组id不能为空！');
        }
        $response = $this->httpClient->get(sprintf('/api/v1/initiate/groups/%s/apps', $groupId));
        if(!$response->isSuccess()){
            $body = $response->toObject();
            return $this->sendErrorResponse(500, '获取失败！', $body->msg ?: $response);
        }
        $data = $response->toArray();
        Tool::runEnum($data, $this->groupAppEnum);
        Tool::runTimestamp($data, $this->groupAppTime);
        return $this->response->setJsonContent($data);
    }

    /**
     * 添加应用组应用
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20170704
     * modify by ck 20170918    可更新学校应用
     */
    public function createAppGroupAppAction()
    {
        $groupId = $this->request->getPost('groupId', 'string');
        $appList = $this->request->getPost('appList');
        $type    = $this->request->getPost('type', 'string');
        $schoolId= $this->request->getPost('schoolId', 'int');
        if (!$groupId) {
            return $this->sendErrorResponse(400, '应用组id不能为空');
        }
        if (!$appList) {
            return $this->sendErrorResponse(400, '列表不能为空');
        }
        if (!in_array($type, ['single', 'all'])) {
            return $this->sendErrorResponse(400, '操作类型不正确');
        }
        foreach($appList as $index => $app){
            $appList[$index]['versionCode'] = intval($app['versionCode']);
        }
        $response = $this->httpClient->postJson(sprintf('/api/v1/initiate/groups/%s/apps', $groupId), $appList);
        if(!$response->isSuccess()){
            $body = $response->toObject();
            return $this->sendErrorResponse(500, '添加失败！', $body->msg ?: $response);
        }
        if ($type == 'all') {
            if (!$schoolId) {
                return $this->sendErrorResponse(400, '学校id不能为空', '所选组已更新成功');
            }
            $successNum = $errorNum = 0;
            foreach($appList as $index => $app){
                $response = $this->httpClient->put(sprintf(
                    '/api/v1/initiate/apps/%s/versions/%s/to/groups?schoolId=%s',
                    $app['packageName'], $app['versionCode'], $schoolId
                ));
                if ($response->isSuccess()){
                    $successNum++;
                }
                else {
                    $errorNum++;
                }
            }
            return $errorNum
                ? $this->sendErrorResponse(500, "失败{$errorNum}个" , "其中更新成功{$successNum}个")
                : $this->sendSuccessResponse("批量更新成功{$successNum}个");
        }
        return $this->sendSuccessResponse('添加成功！');
    }

    /**
     * 删除应用组应用
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20170704
     */
    public function delAppGroupAppAction()
    {
        $groupId     = $this->request->getPost('groupId', 'string');
        $packageName = $this->request->getPost('packageName', 'string');
        if(!$groupId){
            return $this->sendErrorResponse(400, '应用组id不能为空！');
        }
        if(!$packageName){
            return $this->sendErrorResponse(400, '包名不能为空！');
        }
        $response = $this->httpClient->delete(sprintf('/api/v1/initiate/groups/%s/apps/%s', $groupId, $packageName));
        if(!$response->isSuccess()){
            $body = $response->toObject();
            return $this->sendErrorResponse(500, '删除失败！', $body->msg ?: $response);
        }
        return $this->sendSuccessResponse('删除成功！');
    }

    /**
     * 处理组内历史账号
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by ck 20180730
     */
    public function autoCleanUserAction()
    {
        $schoolId = $this->request->getPost('schoolId', 'int');
        $groupIds = $this->request->getPost('groupIds', 'string');
        if (!$schoolId || !$groupIds) {
            return $this->sendErrorResponse(400, '缺少参数');
        }
        try {
            $groupNum = 0;
            foreach ($groupIds as $groupId) {
                $groupUserIds = App::getAppGroupUser($groupId);
                if (!$groupUserIds) {
                    continue;
                }
                //获取正常用户
                $userIds = XhsysUser::find([
                    'columns'    => 'iUserId',
                    'conditions' => 'iSchoolId = :schoolId: AND iUserId IN ({userIds:array}) AND bDelete = 0 AND bHistory = 0 AND bDisable = 0',
                    'bind'       => ['schoolId' => $schoolId, 'userIds' => $groupUserIds]
                ])->toArray();
                $userIds = array_column($userIds, 'iUserId');
                //数量一致则跳过
                if (count($userIds) == count($groupUserIds)) {
                    continue;
                }
                App::modifyAppGroupUser($groupId, $userIds);
                $groupNum++;
            }
            return $this->sendSuccessResponse("处理成功{$groupNum}组");
        } catch (XhException $e) {
            return $this->sendErrorResponse(500, $e->getMessage(), $e->getDescription());
        }
    }

//    public function getApplicationVersionAction()
//    {
//        $appId = $this->request->getPost('appId', 'string');
//        if(!$appId){
//            return $this->sendErrorResponse('应用id不能为空！', null, 400);
//        }
//        $response = $this->httpClient->get(sprintf('/api/v1/applications/%s/versions/', $appId), ['page' => 1, 'size' => 3]);
//        if(!$response->isSuccess()){
//            $body = $response->toObject();
//            return $this->sendErrorResponse('获取失败！', $body->msg ?: $response, 500);
//        }
//        return $this->response->setJsonContent($response->toArray()['content']);
//    }

}